﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Store.Web.Models;

namespace Store.Web.Services
{
    public class PushService
    {
        private readonly string _connectionString;
        public PushService(string connectionString)
        {
            _connectionString = connectionString;
        }

        public void Subscribe(int customerId, string url)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                var exisitingSubscription = storeDbContext.PushSubscriptions.FirstOrDefault(p => p.Url == url);
                if (exisitingSubscription != null)
                    return;

                PushSubscription pushSubscription = new PushSubscription();
                pushSubscription.Url = url;
                pushSubscription.CustomerId = customerId;

                storeDbContext.PushSubscriptions.Add(pushSubscription);
                storeDbContext.SaveChanges();
            }
        }

        public void Unsubscribe(string url)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                var pushSubscription = storeDbContext.PushSubscriptions.FirstOrDefault(p => p.Url == url);
                if (pushSubscription != null)
                {
                    storeDbContext.PushSubscriptions.Remove(pushSubscription);
                    storeDbContext.SaveChanges();
                }
            }
        }

        public string GetCustomerUrl(int customerId)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                var subscription = storeDbContext.PushSubscriptions.FirstOrDefault(p => p.CustomerId == customerId);
                if (subscription != null)
                {
                    return subscription.Url;
                }

                return string.Empty;
            }
        }
    }
}